import random

from common.ConfigUtil import config
from common.DBUtil import DBUtil
from common.RequestsUtil import RequestsUtil
import re

from middle_ware.db_hander import MyDBHandler


def mk_phone():
    """随机生成手机号"""
    phone = '1'+random.choice(['3','5','7','8','9'])
    for i in range(9):
        num = str(random.randint(0,9))
        phone += num
    return phone



def get_token():
    """登录并获取token"""
    req = RequestsUtil()
    res = req.json('post',
                   config.read('http','base_url')+config.read('login','login_url'),
                   json={"mobile_phone":config.read('login', 'phone'),"pwd":config.read('login','pwd')},
                   headers =  eval(config.read('http', 'headers')))
    print(res)
    token_data = {"token": res['data']['token_info']['token'],
                 "member_id":res['data']['id']}
    return token_data

class Context:
    """保存临时替换的数据"""
    phone = config.read("accounts", "mobile_phone")
    pwd = config.read("accounts", "password")
    member_id = config.read("accounts", "member_id")

    @property
    def loan_id(self):
        #Context().loan_id
        db = MyDBHandler()
        """查数据库，获取最新的loan.id作为Context的loan_id属性"""
        loan = db.query("SELECT * FROM loan ORDER BY id DESC;", one=True)
        return str(loan['id'])

    @property
    def above_balance(self):
        db = MyDBHandler()
        db_user_info = db.query('SELECT * FROM member WHERE id =%s;',
                                     args=[self.member_id])
        return str(db_user_info['leave_amount']+1)





def replace_label(target):
    """
    使用data替换target里的标签，不用replace是因为每次只能替换一个
    :param target:
    :return:
    """
    pattern = r"#(.*?)#"
    ctx = Context()
    while re.search(pattern, target):
        # 第一个参数匹配到phone和pwd
        key = re.search(pattern, target).group(1)
        #动态获取key值
        value = getattr(ctx, key, '')
        target = re.sub(pattern, value, target, 1)
    return target

if __name__ == '__main__':
    print(get_token())





